<!--
 * @Description  : 
 * @Autor        : guoxi
 * @Date         : 2022-07-21 14:35:42
 * @LastEditors  : Please set LastEditors
 * @LastEditTime : 2022-09-27 18:51:10
 * @FilePath     : \rpms\src\views\project\create\components\company.vue
-->
<template>
  <el-button
    v-if="!isApproval && !model.dis"
    @click="handleAdd"
    class="btnClass"
    type="primary"
    icon="el-icon-plus"
  />
  <el-table
    :data="model.tableData"
    border
    style="width: 100%"
    :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
  >
    <template #empty>
      <el-empty :image-size="50" description="暂无数据"></el-empty>
    </template>
    <el-table-column type="index" label="序号"> </el-table-column>
    <el-table-column prop="name" label="单位名称"></el-table-column>
    <el-table-column prop="legal" label="法人单位"></el-table-column>
    <el-table-column prop="type" label="单位类型"></el-table-column>
    <el-table-column prop="task" label="承担任务"></el-table-column>
    <el-table-column prop="role" label="单位角色"></el-table-column>

    <el-table-column label="操作" v-if="!isApproval && !model.dis">
      <template #default="{ row, $index }">
        <el-button type="text" @click="handleEdit(row, $index)">编辑</el-button>
        <el-popconfirm
          confirm-button-text="确定"
          cancel-button-text="取消"
          icon="el-icon-info"
          icon-color="red"
          title="确定删除该条记录吗？"
          @confirm="handleDelete(row, $index)"
        >
          <template #reference>
            <el-button type="text">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
  <el-dialog
    :title="model.isEdit ? '修改项目承担单位' : '添加项目承担单位'"
    v-model="model.dialogFormVisible"
    destroy-on-close
    width="45vw"
  >
    <el-form
      :model="model.formData"
      ref="formRef"
      @submit.prevent
      :rules="model.formRules"
      label-width="100px"
    >
      <el-row>
        <el-col>
          <el-form-item label="单位名称" prop="code">
            <el-cascader
              ref="cascader"
              style="width: 100%"
              popper-class="dept-cas"
              v-model="model.formData.code"
              clearable
              filterable
              :options="joinDeptList"
              :props="model.defaultProps"
              @change="handleCheckChangePartake"
              placeholder="输入名称搜索"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item label="法人单位名称" prop="legal">
            <el-input disabled v-model.trim="model.formData.legal"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item label="单位类型" prop="type">
            <el-input disabled v-model.trim="model.formData.type"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col>
          <el-form-item label="单位角色" prop="role">
            <el-select
              style="width: 100%"
              v-model="model.formData.role"
              clearable
              placeholder="请选择"
              value-key="id"
              @change="handleSelected"
            >
              <el-option
                v-for="item in model.roles"
                :key="item.key"
                :label="item.label"
                :value="item.key"
              ></el-option>
            </el-select>
          </el-form-item> </el-col
      ></el-row>

      <el-row>
        <el-col>
          <el-form-item label="承担任务" prop="task">
            <el-input type="textarea" v-model="model.formData.task"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row justify="end">
      <el-button @click="model.dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </el-row>
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, ref, watch } from "vue";
import { postDeptList } from "/@/api/dept";
import { postSysCompanyList } from "/@/api/organization";
import { cloneDeep } from "lodash-es";
import { useRoute } from "vue-router";
export default defineComponent({
  name: "Company",
  props: {
    data: {
      type: Array,
      default: () => []
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },

  emits: ["change"],
  setup(props, ctx) {
    console.log(props, ctx);
    const route = useRoute();
    const isApproval = route.query.mode === "approval" ? true : false;
    const deptTreePartakeRef = ref<HTMLElement | null>(null) as any;
    let joinDeptList = ref([]);
    const formRef = ref<HTMLFormElement | null>(null) as any;
    const cascader = ref<HTMLFormElement | null>(null) as any;
    const model = reactive({
      dis: props.disabled,
      isEdit: false,
      index: 0,
      dialogFormVisible: false,
      defaultProps: {
        children: "children",
        label: "deptDescShrt",
        value: "id",
        checkStrictly: true,
        emitPath: false
      },
      roles: [
        { key: "牵头单位", label: "牵头单位" },
        { key: "参与单位", label: "参与单位" }
      ],
      tableData: [],
      formData: {
        dept: {},
        code: "",
        name: "",
        legal: "",
        type: "",
        task: "",
        role: ""
      },
      formRules: {
        code: [{ required: true, message: "请选择单位", trigger: "change" }],
        role: [
          { required: true, message: "请选择单位角色", trigger: "change" }
        ],
        task: [{ required: true, message: "请输入承担任务", trigger: "change" }]
      }
    });
    const handleSubmit = async () => {
      const isValid = await new Promise(resolve =>
        formRef.value.validate(resolve)
      );
      if (!isValid) return;
      if (model.isEdit) {
        model.tableData[model.index] = cloneDeep(model.formData);
      } else {
        model.tableData.push(model.formData);
      }
      ctx.emit("change", model.tableData);
      model.dialogFormVisible = false;
    };
    const handleAdd = () => {
      model.formData = {
        dept: {},
        code: "",
        name: "",
        legal: "",
        type: "",
        task: "",
        role: ""
      };
      model.isEdit = false;
      model.dialogFormVisible = true;
    };
    const handleEdit = (row, index) => {
      model.index = index;
      model.dialogFormVisible = true;
      model.isEdit = true;
      model.formData = cloneDeep(row);
    };
    const handleDelete = (row, index) => {
      model.tableData.splice(index, 1);
      ctx.emit("change", model.tableData);
    };
    const initDeptList = async () => {
      const { code, data } = await postDeptList({
        pageSize: 0
      });
      let deptList = [];
      if (code === 200) {
        deptList = data.map(item => {
          return {
            id: item.id,
            deptDescShrt: item.deptDescShrt,
            companyLegalName: item.companyLegalName,
            children: item.children
          };
        });
      }
      let companyList = [];
      const res = await postSysCompanyList({
        pageSize: 0
      });
      if (res.code === 200) {
        res.data.list.map(el => {
          companyList.push({
            id: el.id,
            companyLegalName: el.companyLegalName,
            deptDescShrt: el.companyName,
            isEmp: true
          });
        });
      }

      joinDeptList.value = [
        {
          deptDescShrt: "内部单位",
          disabled: true,
          children: deptList,
          id: "0-0"
        },
        {
          deptDescShrt: "外部单位",
          disabled: true,
          children: companyList,
          id: "0-1"
        }
      ];
    };

    const handleCheckChangePartake = (item: any) => {
      console.log(item);
      const selected = cascader.value.getCheckedNodes();
      if (selected.length > 0) {
        const data = selected[0].data;
        model.formData.dept = { deptDescShrt: data.deptDescShrt, id: data.id };
        model.formData.name = data.deptDescShrt;
        model.formData.code = data.id;
        model.formData.legal = data.isEmp
          ? data.deptDescShrt
          : data.companyLegalName;
        model.formData.type = data.isEmp ? "外部" : "内部";
      } else {
        model.formData.name = "";
        model.formData.legal = "";
        model.formData.type = "";
      }
    };

    onMounted(() => {
      initDeptList();
      model.tableData = props.data || [];
    });
    watch(
      () => props.data,
      newvalue => {
        model.tableData = newvalue || [];
      },

      { immediate: false }
    );
    return {
      isApproval,
      handleCheckChangePartake,
      deptTreePartakeRef,
      model,
      formRef,
      handleSubmit,
      handleAdd,
      handleEdit,
      handleDelete,
      joinDeptList,
      cascader
    };
  }
});
</script>
<style lang="scss" scoped>
.btnClass {
  margin-bottom: 10px;
}
</style>
